<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author=>冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace api\modules\admin\controllers;

use api\modules\admin\AuthController;
use common\extend\exception\B5HttpException;
use common\models\system\AppToken;
use common\services\PermissionService;
use common\services\system\MenuService;
use common\services\system\RoleService;

class IndexController extends AuthController
{
    /**
     * 获取用户信息，前端刷新时，都会进行调用
     * 可以用来实时获取用户信息以及判断token是否失效
     * @return array
     * @throws B5HttpException
     */
    public function actionUserInfo(): array
    {
        $userInfo = $this->getUser();
        $user = $userInfo->toArray(['id', 'avatar', 'email', 'nick_name', 'phone', 'sex', 'avatar', 'create_time']);
        $user['dept'] = PermissionService::deptList($this->user_id);
        $user['roles'] = PermissionService::roleList($this->user_id);
        if (PermissionService::isAdmin($this->user_id)) {
            $roles = ['super_admin'];
            $permissions = ['*'];
        } else {
            $roles = array_column($user['roles'], 'role_key');
            $roleMenuList = RoleService::selectRoleMenuListByRole(array_column($user['roles'], 'id'));
            $permissions = MenuService::selectPermsListByMenuId($roleMenuList);
        }
        return $this->success('', ['user' => $user, 'roles' => $roles, 'permissions' => $permissions]);
    }

    /**
     * 获取路由
     */
    public function actionRouters(): array
    {
        return $this->success('', ['list' => PermissionService::menuList($this->user_id)]);
    }

    public function actionLoginOut(): array
    {
        $tokenId = $this->token['id'] ?? '';
        if ($tokenId) AppToken::deleteAll(['id' => $tokenId]);
        return $this->success('成功退出');
    }
}
